package com.rpc.netty.sample.client;

import com.rpc.netty.core.client.RPCFuture;
import com.rpc.netty.core.client.RpcClient;
import com.rpc.netty.core.client.proxy.IAsyncObjectProxy;
import com.rpc.netty.sample.protocol.HelloService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ClientRunner implements ApplicationRunner {
    @Autowired
    private RpcClient rpcClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        async();
    }

    @SneakyThrows
    public void async() {
        int threadNum = 10;
        final int requestNum = 200;
        Thread[] threads = new Thread[threadNum];

        for (int i = 0; i < threadNum; ++i) {
            threads[i] = new Thread(() -> {
                for (int i1 = 0; i1 < requestNum; i1++) {
                    try {
                        IAsyncObjectProxy client = rpcClient.createAsync(HelloService.class);
                        RPCFuture helloFuture = client.call("hello", Integer.toString(i1));
                        String result = (String) helloFuture.get(3000, TimeUnit.MILLISECONDS);
                        //System.out.println(result);
                        System.out.println(result);
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            });
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
    }

    public void sync() {
        for (int i = 0; i < 1000; i++) {
            try {
                HelloService helloService = rpcClient.create(HelloService.class);
                String result = helloService.hello(Integer.toString(i));
                System.out.println(result);
                Thread.sleep(1000);
            } catch (Exception e) {
                log.error("", e);
                e.printStackTrace();
            }
        }
    }
}
